<template>
  <el-dialog v-model="dialogVisible" title="新建中间件" width="1000">
    <div style="display: flex; justify-content: center; align-items: center;margin: 20px 0;">
      <el-form :model="addMiddleWareInfo" label-position="left" label-width="auto" size="large" style="width: 800px"
        :rules="rules" ref="formDom">
        <el-form-item label="中间件名称" prop="name">
          <el-input v-model="addMiddleWareInfo.name" placeholder="填写中间件名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-segmented v-model="addMiddleWareInfo.status" :options="Status" />
        </el-form-item>
        <el-form-item label="协议" prop="protocol">
          <el-input v-model="addMiddleWareInfo.protocol" placeholder="填写协议" />
        </el-form-item>
        <el-form-item label="主机" prop="host">
          <el-input v-model="addMiddleWareInfo.host" placeholder="填写主机" />
        </el-form-item>
        <el-form-item label="业务Id" prop="operationId">
          <el-input v-model="addMiddleWareInfo.operationId" placeholder="填写业务Id" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
        <el-button type="primary" @click="addEngine">
          提交
        </el-button>
        <el-button type="primary" @click="resetForm">
          清空
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div class="container" :class="{ hasForm: showAddWindow == true }">
    <div class="body">
      <div class="box">
        <div class="topBtns">
          <el-button type="primary" class="topBtn" @click="showDialog">新建中间件</el-button>
          <el-button type="primary" class="topBtn" @click="refresh">刷新</el-button>
        </div>
        <!-- 内容展示 -->
        <div class="contents">
          <div class="content">
            <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
              :data="engineArr" style="width: 100%;height: 650px;" max-height="600px" fit="false">
              <el-table-column prop="mid" label="设备标识码mid" width="150" />
              <el-table-column prop="name" label="中间件名称/name" width="150">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.name"></el-input>
                  <div v-else>{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="中间件状态/status" width="150" :formatter="statusMap">
                <template #default="scope">
                  <el-select v-if="scope.row.isEdit" v-model="scope.row.status">
                    <el-option v-for="status in Status" :value="getNoByStatus(status)" :label="status"></el-option>
                  </el-select>
                  <div v-else>{{ statusMap(scope.row, scope.column) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="protocol" label="协议/protocol" width="120">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.protocol"></el-input>
                  <div v-else>{{ scope.row.protocol }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="operationName" label="业务名称/operationName" width="200" />
              <el-table-column fixed="right" label="操作" min-width="200">
                <template #default="scope">
                  <el-button link type="primary" v-if="!scope.row.isEdit"
                    @click.prevent="startEdit(scope.$index, scope.row)">
                    修改
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="saveModify(scope.$index, scope.row)">
                    保存
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="cancelEdit(scope.$index, scope.row)">
                    取消
                  </el-button>
                  <el-button link type="primary" v-if="!scope.row.isEdit" @click.prevent="checkStatus(scope.row)">
                    查询状态
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 页切换 -->
        <div class="bottom">
          <div class="bottom_left">共有&nbsp;{{ total }}&nbsp;项</div>
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRaw } from 'vue'
import { addMiddleWareData, modifyMiddleWare, reqMiddleWareData, reqMiddleWareStatus } from '@/api/middleWare';
import { ElMessage } from 'element-plus';
import { reqOperationData } from '@/api/operation';
import { getStatus, Status, getNoByStatus } from '@/constant/status';
import { useRouter } from 'vue-router';
import { en } from 'element-plus/es/locale/index.mjs';
import { status } from 'nprogress';

// 数据加载
const initData = async () => {
  engineArr.splice(0, engineArr.length)
  engineArr_unprocessed.splice(0, engineArr_unprocessed.length)
  try {
    let res = await reqMiddleWareData(pageNo.value, pageSize.value)
    switch (res.code) {
      case 0:
        engineArr_unprocessed.push(...res.data.records)
        engineArr.push(...processData(res.data.records))
        total.value = res.data.records.length
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  } catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}

// el-dialog
const dialogVisible = ref(false)
const showDialog = () => {
  dialogVisible.value = true
}

// 表单dom
let formDom = ref()
// 启用编辑
const startEdit = (index, row) => {
  row.isEdit = true
}
// 保存修改
const saveModify = async (index, row) => {
  let modifyData={
    id: row.id,
    name: row.name,
    status: row.status,
    protocol: row.protocol,
    host: row.host,
    operationId: row.operationId,
  }
  let res = await modifyMiddleWare(modifyData)
  switch (res.code) {
    case 0:
      ElMessage({
        type: "success",
        message: "修改成功"
      })
      Object.assign(engineArr[index], row)
      Object.assign(engineArr_unprocessed[index], row)
      row.isEdit = false
      break
    case 1:
      setTimeout(() => { $router.push('/login') }, 1000)
      break
    case 2:
      break
  }
  row.isEdit = false
}
// 取消编辑
const cancelEdit = (index, row) => {
  Object.assign(engineArr[index], engineArr_unprocessed[index])
  row.isEdit = false
}

// 状态转换
const statusMap = (row, column) => {
  return getStatus(row.status)
}
// 当前页号
let pageNo = ref(1)
// 页面大小
let pageSize = ref(10)
// 表单显示控件
let showAddWindow = ref(false)
// 新建中间件表单内容
let addMiddleWareInfo = reactive({
  name: '', //中间件名称
  status: null, //状态
  protocol: '', //协议
  host: '', //主机（域名/ip）
  operationId: '' //业务id
})
// 业务表
let operationArr = reactive([])
// 获取的数据(未处理)
let engineArr_unprocessed = reactive([])
// 设备组
let engineArr = reactive([])
// 处理数据
const processData = (data) => {
  return data.map(item => {
    return {
      ...item,
      isEdit: false,
    }
  })
}
// 设备总数
let total = ref(0)
// 路由
let $router = useRouter()
// 校验规则
const rules = {
  name: [
    { type: "string", required: true, message: '请输入中间件名称', trigger: ['blur', 'change'] }
  ],
  protocol: [
    { type: "string", required: true, message: '请输入协议', trigger: ['blur', 'change'] }
  ],
  host: [
    { required: true, message: '请输入主机', trigger: ['blur', 'change'] }
  ],
  operationId: [
    { type: "string", required: true, message: '请输入业务Id', trigger: ['blur', 'change'] }
  ],
}

// 清空表单
const resetForm = () => {
  for (let key in addMiddleWareInfo) {
    addMiddleWareInfo[key] = null
  }
}

//新建中间件确认提交
const addEngine = async () => {
  let validRes = true
  await formDom.value.validate((valid) => {
    if (!valid) {
      validRes = false
      return false
    }
    return true
  })
  if (!validRes || addMiddleWareInfo.status == null) {
    ElMessage({
      type: "error",
      message: '信息缺漏，请检查'
    })
    return;
  }
  try {
    let arr = []
    let reqData = toRaw(addMiddleWareInfo)
    reqData.status = getNoByStatus(addMiddleWareInfo.status)
    reqData.operationId = Number(addMiddleWareInfo.operationId)
    arr.push(reqData)
    let res = await addMiddleWareData(arr)
    switch (res.code) {
      case 0:
        if (res.data.success == true) {
          ElMessage({
            type: "success",
            message: "操作成功"
          })
          resetForm()
          dialogVisible.value = false
          refresh()
        }
        else {
          ElMessage({
            type: "error",
            message: "新建中间件失败"
          })
        }
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  } catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }

}

// 页面改变
const changePage = async (newPage) => {
  pageNo.value = newPage
  await initData()
}
// 查询中间件状态
const checkStatus = async (row) => {
  let mid = row.mid
  try {
    let res = await reqMiddleWareStatus(mid)
    switch (res.code) {
      case 0:
        ElMessage({
          type: 'success',
          message: res.data
        })
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  }
  catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}

// 刷新
const refresh = async () => {
  await initData()
}
onMounted(async () => {
  await initData()
  // 业务列表获取
  let operationRes = await reqOperationData()
  switch (operationRes.code) {
    case 0:
      operationArr.push(...operationRes.data)
      break
    case 1:
      setTimeout(() => { $router.push('/login') }, 1000)
      break
    case 2:
      break
  }
})
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.active {
  color: rgb(24, 148, 197) !important;
}

.hidden {
  display: none !important;
}

.hasForm {
  opacity: 0.3;
  pointer-events: none;
}

.form {
  position: absolute;
  left: 500px;
  top: 200px;
  width: 1200px;
  background-color: #fff;
  color: rgb(156, 153, 153);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 2px 2px 2px rgb(198, 198, 198);

  .formTop {
    border-bottom: 1px solid rgb(207, 202, 202);
    box-sizing: border-box;
    height: 80px;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 20px;
  }

  .formBody {
    width: 100%;
    height: 370px;
    overflow-y: scroll;
    background-color: white;

    .members {
      display: flex;
      width: 100%;
      box-sizing: border-box;
      padding-left: 20px;
      padding-right: 20px;
      height: 50px;
      align-items: center;
      justify-content: center;
      background-color: rgb(170, 220, 224);
      font-weight: 700;
      color: #fff;

      .member {
        flex: 1;
      }
    }

    .inputs {
      display: flex;
      width: 100%;
      box-sizing: border-box;
      background-color: rgb(239, 235, 235);
      height: 50px;
      align-items: center;
      justify-content: center;
      font-weight: 700;
      color: #fff;
      border-bottom: 0.5px solid rgb(210, 203, 203);

      .input {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;

        input,
        select {
          height: 28px;
          width: 90%;
          font-size: 12px;
          padding: 5px;
          box-sizing: border-box;
          background-color: rgb(247, 244, 244);
          border: 0.1px solid rgb(88, 88, 88);
        }
      }

      .btn {
        width: 20px;
        height: 20px;
        font-size: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        color: white;
        border-radius: 50%;
        background-color: red;
        border: none;
        transform: scale(1);
        margin-right: 10px;
        cursor: pointer;
      }

      .btn:hover {
        border: 0.5px solid white;
      }
    }

    .plus {
      display: flex;
      width: 100%;
      height: 40px;
      align-items: center;
      justify-content: center;
      margin-top: 10px;

      .btn {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        font-weight: 700;
        border: none;
        border-radius: 50%;
        background-color: rgb(60, 188, 238);
        color: white;
        cursor: pointer;
        box-sizing: border-box;
      }

      .btn:hover {
        border: 2px solid rgb(135, 129, 129) !important;
      }
    }
  }

  .formBottom {
    width: 100%;
    height: 50px;
    border-top: 1px solid rgb(207, 202, 202);
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: right;
    padding: 20px;
    box-sizing: border-box;
  }
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .body {
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    color: rgb(156, 153, 153);

    .box {
      margin: 20px;
      width: 85%;
      height: 96%;
      background-color: white;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      border: 1px solid rgb(178, 178, 178);
      box-shadow: 0.5px 0.5px 1px 1px rgb(196, 196, 196);

      .topBtns {
        width: 100%;
        height: 5%;
        font-weight: 700;
        margin-left: 20px;
        display: flex;

        .topBtn {
          flex-grow: 0;
          box-sizing: border-box;
          padding-left: 10px;
          padding-right: 10px;
        }
      }


      .contents {
        margin-top: 10px;
        display: flex;
        box-sizing: border-box;
        width: 100%;
        height: 90%;

        .content {
          height: 100%;
          width: 100%;
          box-sizing: border-box;
          flex-direction: column;
        }
      }

      .bottom {
        display: flex;
        width: 100%;
        margin-top: 20px;
        padding-left: 20px;
        padding-right: 20px;
        box-sizing: border-box;
        // height: 50px;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
}
</style>